const fs = require('fs');
const path = require('path');
const sharp = require('sharp');
const pngToIcoModule = require('png-to-ico');
const pngToIco = pngToIcoModule && pngToIcoModule.default ? pngToIcoModule.default : pngToIcoModule;

(async () => {
  try {
    const pngCandidates = [
      path.join(__dirname, '..', 'public', 'icon.png'),
      path.join(__dirname, '..', 'renderer', 'icon.png')
    ];
    const pngPath = pngCandidates.find(p => fs.existsSync(p));
    if (!pngPath) {
      console.error('[icon] No PNG source found at public/icon.png or renderer/icon.png');
      process.exit(1);
    }

    const outDir = path.join(__dirname, '..', 'build');
    const pngDir = path.join(outDir, 'icons', 'png');
    fs.mkdirSync(pngDir, { recursive: true });

    const sizes = [16, 24, 32, 48, 64, 128, 256];
    const pngPaths = [];

    for (const size of sizes) {
      const outPng = path.join(pngDir, `icon-${size}.png`);
      await sharp(pngPath)
        .resize(size, size, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } })
        .png()
        .toFile(outPng);
      pngPaths.push(outPng);
    }

    const icoBuf = await pngToIco(pngPaths);
    const icoPath = path.join(outDir, 'icon.ico');
    fs.writeFileSync(icoPath, icoBuf);
    console.log(`[icon] Generated ${icoPath} from ${path.basename(pngPath)} with sizes: ${sizes.join(', ')}`);
  } catch (err) {
    console.error('[icon] Failed to generate icon:', err && err.stack ? err.stack : err);
    process.exit(1);
  }
})();